/*
 * JFrameServer.java
 *
 * Created on 28 de Outubro de 2008, 13:09
 */
package br.unifor.redes1.odirabel.gui.client;

import br.unifor.redes1.odirabel.ConfigProperties;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author  U013876
 */
public class JFrameClient extends javax.swing.JFrame {

    private Socket socket;
    private String login;
    private BufferedReader input;
    private PrintWriter output;
    private String resposta;

    /** Creates new form JFrameServer */
    public JFrameClient() {
        try {
            initComponents();
            socket = new Socket(ConfigProperties.getInstance().getProperty("ipservidor"), Integer.parseInt(ConfigProperties.getInstance().getProperty("portaservidor")));
            input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            output = new PrintWriter(socket.getOutputStream(), true);
        } catch (UnknownHostException ex) {
            JOptionPane.showConfirmDialog(this, ex.getMessage());
        } catch (IOException ex) {
            JOptionPane.showConfirmDialog(this, ex.getMessage());
        }
    }

    private void login() throws Exception {
        if (jTextField1.getText().equals("")) {
            throw new Exception("Preencha o campo login");
        }

        try {

            final String login = jTextField1.getText();
            output.println("INFORM_USER " + login);
            output.flush();            
            boolean logou = false;
            resposta = input.readLine();
            System.out.println("Respondeu: " + resposta);
            if (resposta.equals("REPLY_USER " + login)) {
                System.out.println("Usuário Logado!");
                JPanelPrincipal panel = new JPanelPrincipal(login, this, socket);
                getContentPane().setVisible(Boolean.FALSE);
                setContentPane(panel);
                getContentPane().setVisible(Boolean.TRUE);
                new Thread(panel).start();
                logou = Boolean.TRUE;
                this.login = login;
                this.addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent arg0) {
                        output.println("DISCONNECT_USER " + login);
                        System.exit(0);
                    }
                });
            }

            if (!logou) {
                JOptionPane.showMessageDialog(this, "Não foi possível se logar.");
            }

        } catch (UnknownHostException ex) {
            JOptionPane.showConfirmDialog(this, ex.getMessage());
        } catch (IOException ex) {
            JOptionPane.showConfirmDialog(this, ex.getMessage());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Client");
        getContentPane().setLayout(new java.awt.CardLayout());

        jLabel1.setText("Login:");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setText("Entrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(132, 132, 132)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap(169, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(106, 106, 106)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(125, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, "card2");

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-408)/2, (screenSize.height-328)/2, 408, 328);
    }// </editor-fold>//GEN-END:initComponents

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
    try {
        login();
    } catch (Exception ex) {
        
        JOptionPane.showConfirmDialog(this, ex.getMessage());
    }
}//GEN-LAST:event_jTextField1ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {
        login();
    } catch (Exception ex) {
        JOptionPane.showConfirmDialog(this, ex.getMessage());
    }
}//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
